#
# fusion.discovery.discover
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Toni Ruottu <toni.ruottu@iki.fi>
#          Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import socket
import logging
from xmlrpclib import ProtocolError
from random import sample, choice
from threading import Thread, currentThread

from messkit.nson import decode
from fusion.discovery.opendht import get
from fusion.discovery.advertise import VERSION, REDUNDANCY

discovery_threads = []

def discover(key, maxvals=10, cb=None):
    salt = choice(range(REDUNDANCY))
    key += VERSION
    key += salt * '\x00'
    if cb is None:
        return _discover(key, maxvals)
    else:
        thread = Thread(target = _run,
                        args = (_discover, cb, key, maxvals),
                        name = 'OpenDHT-discovery-thread')
        thread.setDaemon(True)
        thread.start()

def _discover(key, maxvals):
    try:
        values = set(get(key))
        values = sample(values, min(maxvals, len(values)))
        return map(decode, values) # Beware that tuples come out as lists!
    except socket.timeout:
        logging.warning('Discovery: Timeout connecting to OpenDHT.')
        return None
    except socket.error:
        logging.warning('Discovery: Failed to connect to OpenDHT.')
        return None
    except ProtocolError:
        logging.warning('Discovery: Got HTTP error response from OpenDHT.')
        return None
    except ValueError:
        logging.warning('Discovery: Found garbage in OpenDHT.')
        return None

def _run(f, cb, *args):
    thread = currentThread()
    discovery_threads.append(thread)
    try:
        result = f(*args)
        cb(result)
    finally:
        discovery_threads.remove(thread)
